<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;
use app\admin\model\Member;
use app\admin\model\Organization;
use app\admin\model\Basicdata;
use app\admin\model\Image;
use app\admin\model\Area;
use app\admin\model\Villages;

use think\Db;
use think\Exception;
use think\Request;

class Cadremember extends Base
{

    public function _initialize() {
        parent::_initialize();

        /*$defaultWhere = $this->getDefaultWhere();
        $this->defaultWhere = $defaultWhere;*/
        switch ($this->admin->type) {
            case 0:
                $this->defaultWhere = [];
                break;
            case 1:
                $this->defaultWhere = ['b.cityId' => $this->admin->cityId];
                break;
            case 2:
                $this->defaultWhere = ['b.xianId' => $this->admin->xianId];
                break;
            case 3:
            case 6:
                $this->defaultWhere = ['b.townId' => $this->admin->townId];
                break;
            case 4:
                $this->defaultWhere = ['b.villageId' => $this->admin->villageId];
                break;
            default:
                $this->defaultWhere = [];
                break;
        }
        $this->searchFields = [
            'name' => [
                'label'     => '姓名',
                'field'     => 'name',
                'type'      => 'text',
                'disabled'  => false,
                'condition' => 'like'
            ],
        ];

        // 组织
        $organizationList = Organization::where('isDelete', '2')->select();
        // 职务
        $jobList = Basicdata::where('type', 'job')->select();

        $this->assign('organizationList', $organizationList);
        $this->assign('jobList', $jobList);
    }

    public function index() {
        $request = $this->request;
        if($request->isAjax()){
            $param = $request->param();
            $model = model($this->model);

            // 每页起始条数
            $start = $param['start'];
            // 每页显示条数
            $length = $param['length'];
            // 排序条件
            $columns = $param['order'][0]['column'];
            $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];

            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                $where = array_merge($where, $this->defaultWhere);
            }

            $join = [
                ['__MEMBER__ b', 'b.id = a.memberId'],
                ['__ORGANIZATION__ o', 'o.id = a.organizationId']
            ];
            $field = 'a.id, a.jobId, b.avatar, b.name, b.gender, b.mobile, b.identityNumber, b.cityId, b.xianId, b.townId, b.villageId, o.name as organizationName';
            $list = $model->alias('a')->where($where)->join($join)->field($field)->limit($start, $length)->order($order)->select();

            foreach ($list as $item) {
                // 所在地
                $item['area'] = getArea($item);

                // 职务
                if($item['jobId']){
                    $item['job'] = Basicdata::where(['id' => $item['jobId']])->value('name');
                }
            }
            $count = $model->alias('a')->where($where)->join($join)->count();

            $result = [
                'status' => '1',
                'draw' => $param['draw'],
                'data' => $list,
                'recordsFiltered' => $count,
                'recordsTotal' => $count,
            ];

            return json($result);
        }

        return parent::index();
    }

    public function add(Request $request) {

        return parent::add($request);
    }

    public function addPost(Request $request, $redirect = '') {

        return parent::addPost($request, $this->redirect);
    }

    public function edit(Request $request) {
        $model = model($this->model);
        $id = $request->param('id');
        // Get data info
        $info = $model->find($id);

        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }
        $info['memberName'] = Member::where('id', $info['memberId'])->value('name');
        $info['organizationName'] = Organization::where('id', $info['organizationId'])->value('name');

        return $this->fetch($this->editView, [
            'info' => $info
        ]);
    }

    public function editPost(Request $request, $redirect = '') {

        return parent::editPost($request, $this->redirect);
    }

    public function delete() {
        $model = model($this->model);

        $request = $this->request;
        $id = $request->param('id');
        if($id){
            Db::startTrans();
            try{
                $result = $model->where('id', $id)->delete();
                if($result !== false){
                    // Query执行后的操作
                    $model->_after_delete($id);

                    $logInfo = $this->admin->name . '删除了1条' . $this->model . '数据。';
                    Common::adminLog($request, $logInfo);

                    Db::commit();
                    return $this->success('删除成功！', 'admin/' . strtolower($this->model) . '/index');
                }else{
                    Db::rollback();
                    return $this->error('删除失败！', 'admin/' . strtolower($this->model) . '/index');
                }
            }catch (Exception $e){
                Db::rollback();
                return $this->error($e->getMessage());
            }
        }
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);

            if(isset($filter['cityId']) && $filter['cityId']){
                $where['b.cityId'] = $filter['cityId'];
            }
            if(isset($filter['xianId']) && $filter['xianId']){
                $where['b.xianId'] = $filter['xianId'];
            }
            if(isset($filter['townId']) && $filter['townId']){
                $where['b.townId'] = $filter['townId'];
            }
            if(isset($filter['villageId']) && $filter['villageId']){
                $where['b.villageId'] = $filter['villageId'];
            }
            if(isset($filter['organizationId']) && $filter['organizationId']){
                $where['a.organizationId'] = $filter['organizationId'];
            }
            if(isset($filter['name']) && $filter['name']){
                $where['b.name'] = ['like', '%'.$filter['name'].'%'];
            }
        }

        return $where;
    }
}
